package com.xbh.file.service;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @program: file-center
 * @description:
 * @author: 许宝华
 * @create: 2021-11-30 17:52
 */

@Service
public class FileTransferServiceImpl implements FileTransferService {
    private Logger logger = LoggerFactory.getLogger(FileTransferServiceImpl.class);

    @Autowired
    private MinioService minioService;

    /**
     * 上传
     * @param str
     * @param fileName
     * @return
     */
    @Override
    public String fileUpload(String str, String fileName) {
        //将文件上传到文件服务器
        String uploadUrl = minioService.putStrObject(str, fileName);

        //将返回的地址保存到数据库
        return uploadUrl;
    }

    @Override
    public String fileDownload(String fileName) {
        String resStr = minioService.getStrObject(fileName);
        return resStr;
    }

    @Override
    public JSONObject uploadPicture(MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID() + "-" + originalFilename;
            byte[] bytes = file.getBytes();
            String[] split = fileName.split("\\.");
            minioService.putObject(fileName, bytes, split[split.length - 1]);
            JSONObject response = new JSONObject();
            response.put("fileName", fileName);
            response.put("originalFileName", originalFilename);
            response.put("fileUrl", minioService.getUrl(fileName));
            return response;
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return null;
    }
}
